<!--
 * @Description: 我的跟进
 * @Author: lixianggang
 * @Date: 2022-11-11 15:33:16
 * @LastEditors: shenmengfei
 * @LastEditTime: 2023-06-20
-->
<template>
  <div class="page-wrap" v-loading="pageLoading">
    <NormalForm pageTitle="我的跟进" :operateForm="queryForm" :formList="formList" :enumOpt="enumOpt" @handleQuery="handleQuery" @handleReset="handleReset"></NormalForm>
    <div class="g-card mt16 content-card" v-loading="contentLoading">
      <el-form :model="queryForm" label-width="100px" label-position="left">
        <el-form-item label="选择状态" prop="codeName">
          <el-checkbox-group v-model="queryForm.followStateList">
            <el-checkbox v-for="item in statusList" :label="item.dictValue" :key="item.dictValue">
              {{ item.dictLabel }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div class="all-step">
        <div class="step-item" v-for="(item, index) in showFollowList" :key="index">
          <div class="item-title">{{ item.title }}</div>
          <div class="item-sub">共{{ item.total }}个线索</div>
          <!-- 测试 -->
          <Draggable v-model="item.resultList" :group="groupA" animation="300" dragClass="dragClass" ghostClass="ghostClass" chosenClass="chosenClass"
            @start="onStart(item.resultList)" @add="onAdd(item.title, item)" @end="onEnd(item)">
            <transition-group :style="style">
              <div class="item-card" v-for="(subitem, subindex) in item.resultList" :key="subindex" @mousedown="selecteOne(subitem)">
                <div class="card-top">
                  <div class="top-info" @click="goCustomerDetail(subitem)">
                    <div>
                      <img :src="subitem.avatar" v-if="subitem.avatar" />
                      <img src="@/assets/image/default_avatar.png" v-else />
                    </div>
                    <div>
                      <div class="name">{{ subitem.name }}</div>
                      <div class="channel">{{ subitem.corpFullName }}</div>
                    </div>
                  </div>
                  <div class="edit-icon" v-if="!isNotEdit">
                    <svg-icon icon-class="edit" @click="showEditDialog(subitem)" v-hasPermi="['admin:follow:add']"/>
                  </div>
                </div>
                <div class="card-line"></div>
                <div class="card-bottom">
                  <div>最近沟通：{{ subitem.communicateTimeShow }}</div>
                  <div>{{ subitem.communicateBy }}</div>
                </div>
              </div>
            </transition-group>
          </Draggable>
          <el-button style="width: 100%" v-if="item.resultList.length < item.total" @click="checkMore(item, index)" :loading="item.checkMoreLoading">更多
          </el-button>
        </div>
      </div>
    </div>
    <el-dialog title="填写跟进记录" :visible.sync="editVisible" width="40%" v-loading="dialogLoading">
      <el-form :model="recordform" :rules="rules" ref="recordform" label-width="120px">
        <el-form-item label="跟进状态" prop="followState">
          <el-select v-model="recordform.followState" placeholder="请选择跟进状态" style="width: 60%">
            <el-option v-for="item in statusList" :key="item.id" :label="item.dictLabel" :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="跟进时间" prop="followTime">
          <el-date-picker v-model="recordform.followTime" placeholder="请选择跟进时间" value-format="yyyy-MM-dd" :picker-options="pickerOptions" style="width: 60%"></el-date-picker>
        </el-form-item>
        <el-form-item label="跟进方式" prop="followWay">
          <el-radio-group v-model="recordform.followWay">
            <el-radio v-for="item in followWayOptions" :key="item.dictValue" :label="item.dictValue">
              {{ item.dictLabel }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="" prop="otherWay" v-if="recordform.followWay === '4'" class="other-item">
          <el-input v-model="recordform.otherWay" placeholder="请填写跟进方式" maxlength="10"></el-input>
        </el-form-item>
        <el-form-item label="跟进内容" prop="followContent">
          <el-checkbox-group v-model="recordform.followContent">
            <el-checkbox v-for="item in followContentOptions" :key="item.dictValue" :label="item.dictValue">
              {{ item.dictLabel }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="" prop="otherContent" v-if="recordform.followContent.includes('7')" class="other-item">
          <el-input v-model="recordform.otherContent" placeholder="请填写跟进内容" maxlength="10"></el-input>
        </el-form-item>
        <el-form-item label="附件上传" prop="enclosureUrl">
          <el-upload :before-upload="handleBeforeUpload" action="/" class="avatar-uploader">
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div>{{ this.recordform.fileName }}</div>
          <div>支持jpg/png/pdf等常见图片/文件格式</div>
        </el-form-item>
        <el-form-item label="跟进说明" prop="followRemark">
          <el-input v-model="recordform.followRemark" clearable maxlength="200" type="textarea" show-word-limit rows="4"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="cancelAdd">取 消</el-button>
        <el-button type="primary" @click="saveRecord" :loading="saveLoading">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Draggable from 'vuedraggable'
import {
  getFollowList,
  addFollow,
  getFollowListPage,
  getUserJourney,
  getFollowStatusList,
} from '@/api/operate/automarket'
import UploadSingle from '@/components/UploadAvatars/UploadSingle.vue'
import { uploadInterface } from '@/api/operate/verbalTrick'
import { parseTime } from '@/utils/common'

export default {
  components: { UploadSingle, Draggable },
  computed: {
    showFollowList() {
      return this.followList.filter((item) =>
        this.queryForm.followStateList.includes(item.followState + '')
      )
    },
  },
  data() {
    return {
      queryForm: {
        customerName: '',
        journeyId: null,
        followStateList: [],
        pageSize: 5,
      },
      formList: [
        {
          label: '客户名称',
          value: '',
          prop: 'customerName',
          type: 'INPUT',
          emunName: ''
        },
        {
          label: '用户旅程阶段',
          value: '',
          prop: 'journeyId',
          type: 'SELECT',
          emunName: 'journeyList'
        },
      ],
      enumOpt: {
        journeyList: []
      },
      statusList: [],
      followList: [],
      editVisible: false,
      recordform: {
        followState: '',
        followTime: '',
        followWay: '',
        otherWay: '',
        followContent: [],
        otherContent: '',
        enclosureUrl: '',
        fileName: '',
        followRemark: '',
      },
      rules: {
        followState: [
          { required: true, message: '请选择跟进阶段', trigger: 'change' },
        ],
        followTime: [
          { required: true, message: '请选择跟进时间', trigger: 'change' },
        ],
        followWay: [
          { required: true, message: '请选择跟进方式', trigger: 'change' },
        ],
        otherWay: [
          { required: true, message: '请填写其他跟进方式', trigger: 'blur' },
        ],
        followContent: [
          { required: true, message: '请选择跟进内容', trigger: 'change' },
        ],
        otherContent: [
          { required: true, message: '请填写其他跟进内容', trigger: 'blur' },
        ],
      },
      companyGroupList: [],
      saveLoading: false,
      pageLoading: false,
      dialogLoading: false,
      contentLoading: false,
      followWayOptions: [],
      followContentOptions: [],
      currentItem: '',
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        },
      },
      isNotEdit: false, // 是否可编辑跟进用户旅程阶段
      //   拖拽测试
      drag: false,
      groupA: {
        name: 'site',
        pull: true, //可以拖从
        put: true, //可以拖出
      },
      groupB: {
        name: 'site',
        pull: true,
        put: true,
      },
      style: 'min-height:120px; display: block;',
      // 选中的卡片
      selecteItem: {},
    }
  },
  methods: {
    goCustomerDetail(item) {
      this.$router.push({
        path: '/customerManage/allCustomer/customerDetails',
        query: {
          sid: item.sid,
        },
      })
    },
    async handleBeforeUpload(file) {
      console.log(file)
      if (this.total >= 9) {
        this.$message.error('')
        return false
      }
      if (!this.handleCheckFile(file)) return false
      try {
        const formData = new FormData()
        formData.append('file', file)
        this.dialogLoading = true
        let res = await uploadInterface(formData)
        if (res.code === 200) {
          this.recordform.enclosureUrl =
            window.globalConfig.IMAGE_API + res.data.url
          this.recordform.fileName = file.name
        }
        this.dialogLoading = false
      } catch (error) {
        this.dialogLoading = false
      }
    },
    handleCheckFile(file) {
      const size = file.size / 1024 / 1024
      if (file.type.includes('image/') && size > 2) {
        this.$message.error('图片大小不能超过2M')
        return false
      } else if (size > 20) {
        this.$message.error('文件大小不能超过20M')
        return false
      }
      return true
    },
    showEditDialog(item) {
      this.currentItem = item
      this.editVisible = true
      this.recordform = {
        followState: '',
        followTime: '',
        followWay: '',
        otherWay: '',
        followContent: [],
        otherContent: '',
        enclosureUrl: '',
        followRemark: '',
        fileName: ''
      }
      this.$refs.recordform.resetFields()
    },
    saveRecord() {
      this.$refs.recordform.validate((valid) => {
        if (valid) {
          this.handleSaveRecord()
        } else {
          return false
        }
      })
    },
    handleSaveRecord() {
      const params = {
        ...this.recordform,
        followContent: this.recordform.followContent?.toString(),
        sid: this.currentItem.sid,
        followId: this.currentItem.followId,
      }
      this.saveLoading = true
      addFollow(params)
        .then((res) => {
          this.saveLoading = false
          if (res.code === 200) {
            this.$message.success(res.msg || '操作成功')
            this.editVisible = false
            this.handleQuery()
            this.$refs.recordform.resetFields()
          }
        })
        .catch(() => {
          this.saveLoading = false
        })
    },
    cancelAdd() {
      this.editVisible = false
      this.recordform.fileName = ''
      this.$refs.recordform.resetFields()
    },
    checkMore(item, index) {
      const params = {
        followState: item.followState,
        pageNum: item.pageNum + 1,
        pageSize: 5,
        journeyId: this.queryForm.journeyId,
      }
      console.log(item, index)
      item.checkMoreLoading = true
      getFollowListPage(params)
        .then((res) => {
          item.checkMoreLoading = false
          if (res.code === 200) {
            this.followList[index].resultList.push(...res.data?.rows)
            this.followList[index].pageNum++
          }
        })
        .catch(() => {
          item.checkMoreLoading = false
        })
    },
    handleReset() {
      this.queryForm.customerName = ''
      this.queryForm.journeyId = null
      this.handleQuery()
    },
    handleGetFollowList() {
      this.contentLoading = true
      this.followList = []
      const statusList = this.statusList
      const params = {
        ...this.queryForm,
        followStateList: this.queryForm.followStateList?.toString(),
      }
      this.groupA.pull = true
      this.groupA.put = true
      // 页面展示list
      getFollowList(params)
        .then((res) => {
          if (res.code === 200) {
            this.isNotEdit = res.data.hide
            const data = res.data?.scrmFollowResVOList?.filter(
              (item) => item.followState !== null
            )
            if (res.data.hide) {
              this.groupA.pull = false
              this.groupA.put = false
            }
            statusList.forEach((element) => {
              const isExitState = data.filter(
                (item) => item.followState == element.dictValue
              )
              if (
                isExitState?.length === 0 &&
                this.queryForm.followStateList.includes(element.dictValue)
              ) {
                data.push({
                  followState: element.dictValue,
                  title: element.dictLabel,
                  resultList: [],
                  pageSize: 5,
                  pageNum: 1,
                  total: 0,
                  checkMoreLoading: false,
                })
              }
            })
            data.forEach((element) => {
              if (!element.title) {
                element.title = statusList.filter(
                  (item) => item.dictValue == element.followState
                )?.[0].dictLabel
                element.pageSize = 5
                element.pageNum = 1
                element.checkMoreLoading = false
              }
            })
            data.sort((a, b) => {
              return a.followState - b.followState
            })
            this.followList = data
            this.contentLoading = false
          }
        })
        .catch(() => {
          this.contentLoading = false
        })
    },
    handleGetFollowState() {
      // 获取跟进状态
      return new Promise(async (resolve, reject) => {
        try {
          if (this.queryForm.journeyId) {
            // 除默认旅程，获取状态
            let res = await getFollowStatusList({
              flowId: this.queryForm.journeyId,
            })
            const temp = res.data?.map((element) => {
              element.dictValue = element.flowNodeId
              element.dictLabel = element.flowNodeName
              return element
            })
            // 默认路程，调用字典获取旅程状态
            if (res.code === 200) {
              this.statusList = temp
              this.queryForm.followStateList = temp?.map((item) => item.dictValue)
              resolve()
            }
          } else {
            let res = await this.getDicts('follow_states')
            // 默认路程，调用字典获取旅程状态
            if (res.code === 200) {
              this.statusList = res.data
              this.queryForm.followStateList = res.data.map((item) => item.dictValue)
              resolve()
            }
          }
        } catch (error) {
          reject(error)
        }
      })
    },
    handleQuery() {
      this.contentLoading = true
      this.handleGetFollowState()
        .then(() => {
          this.handleGetFollowList()
        })
        .catch((err) => {
          console.log(err)
          this.contentLoading = false
        })
    },
    //开始拖拽事件
    onStart(item) {
      this.drag = true
      console.log(item, '=====')
      if (!this.groupA.pull) {
        this.$message.error('当前为自动跟进类型旅程')
      }
    },
    //拖拽结束事件
    async onAdd(item, newArr) {
      this.drag = false
      console.log(item, '=====123')
      newArr.total++
      var newState = ''
      newState = this.statusList.filter((item1) => {
        if (item1.dictLabel == item) {
          return item1
        }
      })
      console.log(newState, newArr, '====')

      addFollow({
        followState: newState[0].dictValue,
        sid: this.selecteItem.sid,
        followId: this.selecteItem.followId,
        followWay: '0',
        followContent: '0',
        followTime: parseTime(new Date(), '{y}-{m}-{d}'),
      })
        .then((res) => {
          if (res.code === 200) {
            // this.$message.success(res.msg || "操作成功!");
            // this.handleGetFollowList();
          }
        })
        .catch((error) => {
          this.handleGetFollowList()
        })
    },
    // 点击移动项
    selecteOne(item) {
      this.selecteItem = item
      // console.log(parseTime(new Date(), "{y}-{m}-{d}"));
      console.log(item, '=====1')
    },
    onEnd(item) {
      console.log(item, '====结束')
      item.total--
    },
  },
  mounted() {
    this.handleQuery()
    getUserJourney().then((res) => {
      res.data.forEach(item => {
        this.enumOpt.journeyList.push({ dictLabel: item.flowName, dictValue: item.flowId })
      })
    })
    this.getDicts('follow_way').then((res) => {
      if (res.code === 200) {
        this.followWayOptions = res.data
      }
    })
    this.getDicts('follow_content').then((res) => {
      if (res.code === 200) {
        this.followContentOptions = res.data
      }
    })
  },
}
</script>

<style lang="scss" scoped>
@import '@/styles/base.scss';

.page-wrap {
  height: 100%;

  .search-item {
    display: flex;
    justify-content: space-between;
    margin: 20px;

    div {
      margin-right: 16px;
    }

    .el-input {
      width: 210px;
    }

    .el-select {
      width: 190px;
    }
  }

  .content-card {
    padding: 16px 0 20px 20px;
    .all-step {
      display: flex;
      .step-item {
        background: #f6f6f6;
        border-radius: 4px;
        padding: 16px;
        width: 20%;
        height: 600px;
        overflow-y: scroll;
        margin-right: 20px;
        flex-shrink: 0;
        overflow-x: scroll;

        .item-title {
          font-size: 18px;
          font-weight: 600;
          color: #2a2a2a;
          line-height: 25px;
        }

        .item-sub {
          font-size: 14px;
          color: #999999;
          line-height: 20px;
          margin-top: 5px;
        }

        .item-card {
          background: #ffffff;
          border-radius: 6px;
          padding: 14px;
          margin: 16px 0;

          &:hover .edit-icon {
            cursor: pointer;
            display: block;
          }

          .edit-icon {
            // display: none;
          }

          .card-top {
            display: flex;
            justify-content: space-between;

            .top-info {
              display: flex;

              img {
                width: 48px;
                height: 48px;
                margin-right: 15px;
                border-radius: 50%;
              }

              .name {
                font-size: 14px;
                font-weight: 400;
                color: #2a2a2a;
                line-height: 20px;
              }

              .channel {
                background: #EBEEFF;
                border-radius: 2px;
                padding: 2px 8px;
                font-size: 12px;
                font-weight: 400;
                color: #082aff;
                line-height: 17px;
                margin-top: 6px;
              }
            }
          }

          .card-line {
            height: 1px;
            width: 100%;
            margin: 18px 0 10px;
            background-color: #eeeeee;
          }

          .card-bottom {
            display: flex;
            justify-content: space-between;
            font-size: 13px;
            color: #999999;
            line-height: 18px;
          }
        }
      }
    }
  }

  .other-item {
    padding-top: 0 !important;
  }

  .avatar-uploader {
    width: fit-content;
    border: 1px dashed #DCDFE6;
  }
}

/*定义要拖拽元素的样式*/
.ghostClass {
  background-color: blue !important;
}
.chosenClass {
  background-color: #fff !important;
  opacity: 1 !important;
}
.dragClass {
  background-color: #fff !important;
  opacity: 1 !important;
  box-shadow: none !important;
  outline: none !important;
  background-image: none !important;
}
.itxst {
  margin: 10px;
}
.title {
  padding: 6px 12px;
}
.col {
  width: 40%;
  flex: 1;
  padding: 10px;
  border: solid 1px #eee;
  border-radius: 5px;
  float: left;
}
.col + .col {
  margin-left: 10px;
}

.item {
  padding: 6px 12px;
  margin: 0px 10px 0px 10px;
  border: solid 1px #eee;
  background-color: #f1f1f1;
}
.item:hover {
  background-color: #fdfdfd;
  cursor: move;
}
.item + .item {
  border-top: none;
  margin-top: 6px;
}
</style>
